/*
 * @Author: wwssaabb
 * @Date: 2021-08-26 16:23:16
 * @LastEditTime: 2021-09-03 08:42:42
 * @FilePath: \hospitable-rental-for-react\src\redux\reducer.js
 */

import { combineReducers } from 'redux'
import axios from 'axios'

import { user_action,records_action } from '../utils'

import {} from './actions'

import { 
  LOGIN,
  LOGOUT,
  RECORD_ADD,
  RECORD_CLS
 } from './constant'

 //管理用户登录的数据
const initUser=user_action.get()
const user=(state=initUser,action)=>{
  switch(action.type){
    case LOGIN: //登录
      user_action.set(action.data)
      records_action.set([])
      return action.data
    case LOGOUT:  //登出
      user_action.remove()
      records_action.remove()
      return  null
    default:
      if(state)axios.defaults.headers.common['Authorization']=state.token
      return state
  }
}

//管理用户浏览记录
const initRecords=records_action.get()?records_action.get():[]
const record=(state=initRecords,action)=>{
  const {set,remove}=records_action
  switch(action.type){
    case RECORD_ADD:
      let arr
      if(state.length<100){
        arr=[action.data,...state]
      }else{
        arr=[action.data,...state.slice(0,99)]
      }
      set(arr)
      return [...arr]
    case RECORD_CLS:
      console.log('remove')
      remove()
      return []
    default:
      return state
  }
}

export default combineReducers({
  user,
  record
})